#include "UdpClient.hpp"
#include <iostream>
#include <cstring>
#include <string.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Common.hpp"
#include <pthread.h>
#include <signal.h>


int sockfd = -1;
struct sockaddr_in server;


void ClientQuit(int signo)
{
    (void)signo;
    const std::string quit = "Quit!";
    int n = ::sendto(sockfd,quit.c_str(),quit.size(),0,CONV(&server),sizeof(server));
}


void* Recver(void* args)
{
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd,buffer,sizeof(buffer)-1,0,CONV(&temp),&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl;
        }
    }
    return nullptr;
}

// ./client_udp serverip serverport
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serverip serverport" << std::endl;
        Die(USAGE_ERR);
    }
    signal(2,ClientQuit);
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //1.创建socket
    sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if (sockfd < 0)
    {
        std::cerr << "scoket error" << std::endl;
        Die(SOCKET_ERR);
    }
    //1.1填充server信息
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport); //要被发送给对方的,即要发送到网络中
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    pthread_t tid;
    pthread_create(&tid,nullptr,Recver,nullptr);



    //1.2启动的时候,给服务器推送消息即可
    const std::string online = "...来了哈!";
    int n = ::sendto(sockfd,online.c_str(),online.size(),0,CONV(&server),sizeof(server));


    //2.client done
    while(true)
    {
        std::cout << "please Enter# " << std::endl;
        std::string message;
        std::getline(std::cin,message);
        int n = ::sendto(sockfd,message.c_str(),message.size(),0,CONV(&server),sizeof(server));
        (void)n;
    }

    return 0;
}
